import React, { PureComponent } from 'react';
import { Badge, Button, Dropdown, Input, Menu, Select } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import BaseComp from '../../Base/BaseComp';
import { getStorage, isObjectValEqual, QueryFilter } from 'jh-utils';
import { find, forEach, isEmpty, map } from 'lodash-es';
import styles from './index.module.less';
import { connect } from 'dva';

const activityData = {
    'appCode': 'EXPENSE_REIMBURSEMENT',
    'appName': '员工费用报销',
    'javaType': 'com.jianhui.expense.reimbursement.domain.ExpenseReimbursement',
    'count': 10,
    'details': [
        { 'taskCode': 'bpm0022c085', 'taskName': '部门审批', 'count': 1 },
        { 'taskCode': 'bpm0a85930f', 'taskName': '部长审批', 'count': 1 },
        { 'taskCode': 'bpm3d902ffc', 'taskName': '财务审批', 'count': 1 },
        { 'taskCode': 'bpm3ff5ee85', 'taskName': '费用填报', 'count': 5 },
        { 'taskCode': 'bpmbeb0042e', 'taskName': '销售组长审批', 'count': 2 },
    ],
};

/**
 * 任务类型
 * @type {{TODO: string, END: string, MY: string}}
 */
export const ACTIVITY_VALUES = {
    MY: 'MY', // 我的
    TODO: 'TODO', // 待办
    END: 'END', // 已办
};
@connect(({ global }) => ({ userTask: global && global.userTask || [] }))
export default class ActivityRadioGroup extends BaseComp {

    initState(props) {
        return {
            ...super.initState(props),
            activity: props.activity || '', // 对应 ACTIVITY_VALUES 的值
            taskCode: props.activityTaskCode || 'all', // 任务节点。'all'表示所有待办
        };
    }

    componentDidMount() {
        super.componentDidMount();
        // 获取任务节点
        this.fetchTask();
    }

    componentDidUpdate(preProps, prepState) {
        super.componentDidUpdate && super.componentDidUpdate(preProps, prepState);

        if (!isObjectValEqual(preProps, this.props, ['activity', 'activityTaskCode'])) {
            if (this.props.activity && this.props.activityTaskCode) {
                this.setState({
                    activity: this.props.activity,
                    taskCode: this.props.activityTaskCode,
                });
            }
        }
    }

    fetchTask() {
        let { appins } = this.props;
        if (appins && appins.fetchUserTask) {
            appins.fetchUserTask();
        }
    }

    getFilter(searchData) {
        const filter = new QueryFilter(QueryFilter.AND);
        const fAppCode = this.getAppCode();
        const accountInfo = getStorage('accountInfo') || {};
        const { userId = '' } = accountInfo;
        if (!isEmpty(searchData) && searchData.activity) {
            const activity = searchData.activity;
            switch (activity) {
                case 'END':
                    // filter.andEqual('activityInfo.taskCode', 'end');
                    const hqlEND = '(SELECT i.dataId FROM com.jianhui.act.engine.domain.ActivityInstanceProgress p JOIN p.instance i ' +
                        `WHERE i.appCode='${fAppCode}' AND p.status='TREATED' AND p.updateInfo.userId=${userId} GROUP BY i.dataId)`;
                    filter.andIn('id', hqlEND);
                    break;
                case 'TODO':
                    filter.andIsNotNull('activityInfo.taskKey');
                    filter.andNotEqual('activityInfo.taskKey', '');
                    filter.andNotEqual('activityInfo.taskKey', 'start');
                    filter.andNotEqual('activityInfo.taskKey', 'end');
                    if (!isEmpty(searchData.taskCode) && searchData.taskCode !== 'all') {
                        filter.andEqual('activityInfo.taskCode', searchData.taskCode);
                    }
                    const hql = '(SELECT it.id FROM ActivityInstanceActor it ' +
                        'JOIN it.instance i WHERE i.dataId=o.id AND i.currentTask=o.activityInfo.taskKey ' +
                        `AND it.taskKey=i.currentTask AND i.appCode='${fAppCode}' ` +
                        'AND i.procDefKey=o.activityInfo.procDefKey ' +
                        'AND it.taskCode=o.activityInfo.taskCode ' +
                        `AND it.actor.id=${userId} )`;
                    filter.andExists(hql);
                    break;
                default:
                    break;
            }
        }
        return filter;
    }

    handleActChange(activity, taskCode = 'all') {
        const { onChange } = this.props;
        const newState = {
            taskCode,
            activity,
        };
        this.setState(newState, () => {
            const filter = this.getFilter(newState);
            // console.log('filter', filter, newState);
            onChange && onChange(filter, newState);
        });
    }

    /**
     * 改变“待办-任务节点”之后
     * @param taskCode {string} 任务节点的 taskCode
     */
    hdlChangeTodo = (taskCode) => {
        this.handleActChange(ACTIVITY_VALUES.TODO, taskCode);
    };

    /**
     * 点击 select 框， 如果是当前按钮点击，不做操作，否则重新请求数据
     */
    clickSelect() {
        const { taskCode, activity } = this.state;
        if (ACTIVITY_VALUES.TODO !== activity) {
            this.handleActChange(ACTIVITY_VALUES.TODO, taskCode);
            this.setState({ activity: ACTIVITY_VALUES.TODO });
        }
    }

    render() {
        let { taskCode, activity } = this.state;
        let { userTask } = this.props;
        let task = find(userTask, task => task.appCode === this.getAppCode()) || {};
        let taskList = [], totalTask = 0;
        taskList = task.details || [];
        totalTask = taskList.length;

        return (
            <Input.Group compact style={{ width: 'auto', whiteSpace: 'nowrap' }}>
                <Button type={ACTIVITY_VALUES.MY === activity ? 'primary' : ''}
                        onClick={() => {
                            this.handleActChange(ACTIVITY_VALUES.MY, taskCode);
                        }}>{this.formatMsgByCn('我的')}</Button>
                {
                    totalTask <= 0 ? (
                        <Button type={ACTIVITY_VALUES.TODO === activity ? 'primary' : ''}
                                onClick={() => {
                                    this.handleActChange(ACTIVITY_VALUES.TODO, taskCode);
                                }}>{this.formatMsgByCn('待办')}</Button>
                    ) : (
                        <Select
                            value={taskCode}
                            onChange={this.hdlChangeTodo}
                            onClick={this.clickSelect.bind(this)}
                            className={ACTIVITY_VALUES.TODO === activity ? styles.selActive : ''}
                            style={{ minWidth: 80 }}
                            dropdownStyle={{ minWidth: 180 }}
                        >
                            <Select.Option key={'all'} value={'all'}>
                                {this.formatMsgByCn('待办')}
                            </Select.Option>
                            {
                                map(taskList, (task) => (
                                    <Select.Option key={task.taskCode} value={task.taskCode}>
                                        {task.taskName} {task.count > 0 ? `(${task.count})` : ''}
                                    </Select.Option>
                                ))
                            }
                        </Select>
                    )
                }
                <Button type={ACTIVITY_VALUES.END === activity ? 'primary' : ''}
                        onClick={() => {
                            this.handleActChange(ACTIVITY_VALUES.END, taskCode);
                        }}>{this.formatMsgByCn('已办')}</Button>
            </Input.Group>
        );
    }
}